class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> vv;
        int i = 0, j = i + 1;
        while (i < nums.size()) {
            j = i + 1;
            while (j < nums.size()) {
                int left = j + 1;
                int right = nums.size() - 1;
                long long ret=(long long)target-nums[i] - nums[j];
                while (left < right) {
                    int sum = nums[left] + nums[right];
                    if (sum < ret) {
                        left++;
                    } else if (sum > ret) {
                        right--;
                    } else {
                        vv.push_back(
                            {nums[i], nums[j], nums[left], nums[right]});
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                    }
                }
                j++;
                while (j < nums.size() && nums[j] == nums[j - 1])
                    j++;
            }
            i++;
            while (i < nums.size()&& nums[i] == nums[i - 1])
                i++;
        }
        return vv;
    }
};